<template>
	<div class="detail-wrapper">
		<van-nav-bar title="事件单详情" left-text="返回" left-arrow @click-left="onClickLeft" />
		<!-- <van-pull-refresh class="content" v-model="loading" @refresh="onRefresh"> -->
		<div class="content">
			<van-tabs v-model:active="active">
				<van-tab title="事件单信息">
					<v-form-render ref="formRef" :form-json="finallyFormJson" :option-data="optionData" :mixMode="true" v-if="!formLoading">
						<template #extendSlot>
							<div class="extend-wrapper">
								<div class="extend-item" :span="12" v-for="(item, index) of extendFields" :key="index">
									<div class="extend-item-label">{{ item.fieldName }}</div>
									<div class="extend-item-value">{{ item.result || '--' }}</div>
								</div>
							</div></template
						>
					</v-form-render>
				</van-tab>
				<van-tab title="处置流程">
					<div class="process-wrapper">
						<process-node
							v-for="(item, index) of processData"
							:title="eventDetail.eventTitle"
							:creator="eventDetail.creator"
							:key="index"
							:datas="item"
							@view="showDialog"
						/>
					</div>
				</van-tab>
			</van-tabs>
		</div>
		<!-- </van-pull-refresh> -->
		<!-- 查看弹窗 -->
		<ViewDialog ref="viewDialogRef" />
	</div>
</template>
<script setup>
import formJson from '/@/utils/dialogTable.json';
import { getDetail, getHandleFlow } from '/@/api/myTodo/index';
import { getEvenPage } from '/@/api/myEvent/index';
import { getAllDetailJson } from '/@/utils/transform.ts';
import { useDictAsync } from '@cqdcg/admin/hooks/dict';
import ProcessNode from './components/processNode.vue';
import ViewDialog from './components/viewDialog.vue';

const active = ref(0);
const route = useRoute();
const router = useRouter();
const onClickLeft = () => {
	router.go(-1);
};

// const loading = ref(false);
// const onRefresh = () => {
// 	try {
// 		init();
// 		loading.value = false;
// 	} catch (error) {
// 		loading.value = false;
// 	}
// };

const init = async () => {
	showLoadingToast({
		message: '加载中...',
		forbidClick: true,
		duration: 0,
	});
	try {
		await initOptionData();
		await getFinallyFormJson();
		formLoading.value = false;
		await getEventDetail();
		await getHandleFlows();
		closeToast();
	} catch {
		closeToast();
	}
};

// 获取事件单详情
const formRef = ref();
const formLoading = ref(true);
const eventDetail = ref({});
const getEventDetail = async () => {
	if (route.query.id) {
		try {
			const res = await getDetail(route.query.id);
			eventDetail.value = res.data;
			res.data.sex = res.data.sex ? res.data.sex.toString() : '';
			res.data.longLat = res.data.lat ? res.data?.lon + ',' + res.data?.lat : '';
			res.data.regionCode = stringsToArray(
				res.data.belongProvince,
				res.data.belongCity,
				res.data.belongCounty,
				res.data.belongStreet,
				res.data.belongCommunity
			).filter(Boolean);
			res.data.listFile = Array.isArray(res.data?.listFile) ? res.data.listFile : JSON.parse(res.data.listFile);
			nextTick(() => {
				if (formRef.value) {
					formRef.value.setFormData(res.data);
					nextTick(() => {
						formRef.value.setReadMode();
					});
				}
			});
		} catch {
			nextTick(() => {
				if (formRef.value) {
					formRef.value.setReadMode();
				}
			});
		}
	}
};
const stringsToArray = (...strings) => {
	return [...strings];
};

// 获取完整formjson
const finallyFormJson = ref({});
const getFinallyFormJson = async () => {
	finallyFormJson.value = getAllDetailJson(formJson, true);
};

// 处置流程
const processData = ref([]);
// 获取流程信息
const extendFields = ref([]); // 扩展字段
const getHandleFlows = async () => {
	if (route.query.eventNum) {
		const res = await getHandleFlow({ logId: route.query.eventNum });
		if (res.data.length > 0) {
			res.data[0].isStart = true;
		}
		processData.value = res.data;
		const extendFieldArr = [];
		getExtendField(res.data, extendFieldArr);
		extendFields.value = extendFieldArr;
	}
};

// 获取扩展字段
const getExtendField = (datas, filedArr) => {
	datas.forEach((item) => {
		if (item.taskOrderOutputs && item.taskOrderOutputs.length > 0) {
			item.taskOrderOutputs.forEach((out) => {
				if (out.isAddToExtends) {
					if (out.fieldValue && out.fieldValue.length > 0) {
						// 附件或枚举
						if (out.fieldValue[0].indexOf('{') !== -1) {
							const result = JSON.parse(out.fieldValue[0]);
							if (out.fieldCode === 'attachment') {
								// 附件
								out.result = result;
							} else if (Array.isArray(result)) {
								// 多选枚举
								out.result = result.map((i) => i.optionKey);
							} else {
								// 单选枚举
								out.result = result.optionKey;
							}
						} else {
							out.result = out.fieldValue[0];
						}
					}
					filedArr.push(out);
				}
			});
		}
		if (item.listFile && item.listFile.length > 0) {
			getExtendField(item.listFile, filedArr);
		}
	});
};

// 初始化选项
const optionData = ref({});
const initOptionData = async () => {
	const res = await getEvenPage({ type: 2 });
	const Applydata = res.data
		? JSON.parse(JSON.stringify(res?.data))?.map((item) => {
				return {
					value: item.eventName,
					label: item.eventName,
					event: item.eventName,
					code: item.sourceAppCode,
					name: item.sourceApplicationName,
				};
		  })
		: [];
	const { event_level, event_scale, event_sex, event_label, event_appeal_type } = await useDictAsync(
		'event_level',
		'event_scale',
		'event_sex',
		'event_label',
		'event_appeal_type'
	);
	optionData.value = {
		eventType: Applydata,
		eventLevel: event_level,
		scale: event_scale,
		sex: event_sex,
		label: event_label,
		appeal: event_appeal_type,
	};
};

// 查看处置详情
const viewDialogRef = ref();
const showDialog = (name, datas) => {
	viewDialogRef.value.showDialog(name, datas);
};

onMounted(() => {
	init();
});
</script>
<style lang="scss" scoped>
:deep(.border) {
	background: linear-gradient(180deg, #1989fa 0%, #409eff 100%);
}

:deep(.el-card__body) {
	.el-col {
		height: auto !important;
	}
}

:deep(.el-form) {
	margin-bottom: 100px;
}

:deep(.el-form-item) {
	.el-form-item__label {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		height: auto !important;
		min-height: 36px !important;
		line-height: 20px !important;
		text-align: left;
		word-wrap: break-word;
		white-space: pre-line;
	}

	.el-form-item__content {
		margin-bottom: 20px;
	}
}

.detail-wrapper {
	display: flex;
	flex-direction: column;
	width: 100%;
	height: 100%;
	background-color: #fff;

	.content {
		box-sizing: border-box;
		flex: 1;
		width: 100%;
		overflow-y: auto;

		.van-tabs {
			display: flex;
			flex-direction: column;
			height: 100%;
		}

		:deep(.van-tabs__content) {
			box-sizing: border-box;
			flex: 1;
			overflow-y: auto;
		}
	}

	.process-wrapper {
		box-sizing: border-box;
		width: 100%;
		padding: 20px;
	}
}

:deep(.van-action-sheet) {
	height: 500px !important;
	max-height: 500px !important;
}

.extend-item {
	box-sizing: border-box;
	width: 100%;
	margin-bottom: 20px;

	&-label {
		width: 100%;
		margin-right: 12px;
		margin-bottom: 10px;
		font-size: 14px;
		color: #606266;
		text-align: left;
	}

	&-value {
		width: 100%;
		padding: 7px 0;
		margin-bottom: 40px;
		font-size: 14px;
		color: #303133;
		word-break: break-all;
		background-color: #f8f8f8;
	}
}
</style>
